// mircoApp/ai-create/VideoCreation/index.js
let app = getApp();
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');

Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    imgPath: app.globalData.imgPath,
    business_id: 0,
    name: '', //封面
    drive_type: '0', //驱动类型：0=文案；1=音频
    fileList: [],
    voice_speech: 35, //配音语速，默认1.0。取值：[0.5,2.0]，支持小数
    voice_volume: 10,
    video_volume: 2,
    paperwork_total: 0,
    minute: 0,

    activeMusic: 0,
    selectRole: {},
    showWords: {},

    textConfig: [{
        icon: 'icon-peizhi',
        name: '配置',
        pop: 'showConfig'
      },
      //  {
      //   icon: 'icon-duanju',
      //   name: '断句'
      // }, 
      {
        icon: 'icon-yinle',
        name: '音乐',
        pop: 'showMusic'
      }, {
        icon: 'icon-icon_dingdan_11',
        name: '文案',
        pop: 'showCopywriter'
      }, {
        icon: 'icon-peiyin',
        name: '配音',
        pop: 'showDub'
      }
    ],
    showConfig: false,
    actions: [{
        name: '中文',
      },
      {
        name: '英文',
      }
    ],
    showMusic: false,
    showCopywriter: false,
    showDigitalHuman: false,

    role_list: [],
    showWords: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.form = {};
    this.data.business_id = options.business_id;
    this.createVideoLock = false;
    this.getData();
    this.initData();
  },
  onClickVal(e) {
    let {
      name,
      val
    } = e.currentTarget.dataset;
    this.setData({
      [name]: val
    });

    if (name == 'selectRole') {
      this.essayList = null;
    }
    
    this.AudioPause();
  },
  selectVal(e) {
    let {
      name,
      val
    } = e.currentTarget.dataset;
    this.setData({
      [name]: val
    });
    this.form[name] = val;
  },
  async getData() {
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.video');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        body_id: this.options.body_id || 0,
        business_id: this.options.business_id || 0
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.data.themeBaseColor
    });
    this.setData(data);
    this.getWorkData();
    if (data.body && data.body.id) {
      this.form.body_id = data.body.id;
    }
  },
  async getWorkData() {
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.paperwork');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.options.business_id || 0
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);

    this.setData(data);
  },

  //视频封面上传
  afterRead(event) {
    wx.showLoading({
      title: '上传中',
    })
    let {
      file
    } = event.detail;
    let urlStr = app.getNetAddresss('upload.uploadPic');
    wx.uploadFile({
      url: urlStr,
      filePath: file.url,
      name: 'file',
      formData: null,
      success: (res) => {
        wx.hideLoading();
        let _res = JSON.parse(res.data);
        this.form.cover_img = _res.data.img;
        const {
          fileList = []
        } = this.data;
        fileList.push({
          ...file,
          url: res.data.img_url
        });
        this.setData({
          fileList
        })
      },
      fail: (err) => {
        wx.hideLoading()
      }
    });
  },
  delCover_img(){
    this.setData({
      fileList: []
    })
  },
  onChangeTab(e) {
    this.form.drive_type = e.detail.name;
    this.setData({
      drive_type: e.detail.name
    });
  },
  onPreviewVideo(e) {
    let {
      url
    } = e.currentTarget.dataset;
    wx.previewMedia({
      sources: [{
        url: url,
        type: 'video'
      }],
      current: 0,
      fail() {
        wx.showToast({
          title: '预览视频失败',
          icon: 'none'
        });
      },
    });
  },
  getVoice() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: [".mp3", "mp3", ".wav", "wav", ".m4a", "m4a", ], // 根据需要限制文件类型
      success: (res) => {
        this.uploadAudioM(res.tempFiles[0].path);
      }
    });
  },
  uploadAudioM(videoData) {
    let urlStr = app.getNetAddresss("upload.uploadPic");
    urlStr += "&upload_type=audio";
    wx.showLoading({
      title: '上传音频中',
    });
    this.form.video_duration = null;
    this.setData({
      Progress: 0
    })
    let uploadTask = wx.uploadFile({
      url: urlStr, //仅为示例，非真实的接口地址
      filePath: videoData,
      name: "file",
      formData: {},
      success: (resdata) => {
        wx.hideLoading();
        let res = JSON.parse(resdata.data);
        if (res.result != 1) return app.tips(res.msg);
        this.form.voice_url = res.data.img;
        
        console.log('地址 ===', res.data);
        this.setAudioURL(res.data.img_url);
        this.setData({
          hasAudio: true
        });
      },
      fail: () => {
        app.tips('上传音频出错');
        wx.hideLoading();
      }
    });

    uploadTask.onProgressUpdate((res) => {
      this.setData({
        Progress: res.progress //上传进度
      });
    })
  },
  setAudioURL(src){
    this.innerAudioContext.src = src;
    this.AudioPlay();
  },
  getAudioDuration() {
    if(this.data.showMusic || this.data.showDub || this.data.drive_type == 0) return;
    if (!this.form.video_duration) {
      let _duration = Math.floor(this.innerAudioContext.duration);// 取整秒数
      this.form.video_duration = _duration;
      this.setData({
        audioDuration: this.formatDuration(_duration)
      })
      this.minCreatComponent();
    }
  },
  formatDuration(duration) {
    // 将秒数转为 MM:ss  分钟：秒数
    const totalSeconds = duration; 
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;

    const minutesString = minutes.toString().padStart(2, '0');
    const secondsString = seconds.toString().padStart(2, '0');

    return `${minutesString}:${secondsString}`;
  },
  AudioPlay() {
    this.innerAudioContext.play();
  },
  AudioPause() {
    this.innerAudioContext.pause();
  },
  onClickAudio() {
    let name = this.data.AudioStatus ? 'AudioPause' : 'AudioPlay';
    this[name]();
  },
  resetAudio(){
    this.form.video_duration = null;
    this.form.voice_url = null;
    this.setData({
      hasAudio: false
    });
    this.AudioPause();
  },
  initData() {
    this.setData({
      ['video_set.voice_speech']: this.mapVSSliderValue(this.data.voice_speech, 0.5, 2.0),
      ['video_set.voice_volume']: this.mapVSSliderValue(this.data.voice_volume, 0, 10.0),
      ['video_set.video_volume']: this.mapVSSliderValue(this.data.video_volume, 0, 10.0)
    });
    if (!this.innerAudioContext) {
      this.innerAudioContext = wx.createInnerAudioContext({
        useWebAudioImplement: false
      });
      this.innerAudioContext.autoplay = true //设置自动播放
      this.innerAudioContext.onTimeUpdate((res) => {
        this.getAudioDuration();
      });
      this.innerAudioContext.onPlay((res) => {
        this.setData({
          AudioStatus: 1 //正在播放
        })
      });
      this.innerAudioContext.onPause((res) => {
        this.setData({
          AudioStatus: 0 //暂停播放
        })
      });
      this.innerAudioContext.onEnded((res) => {
        this.setData({
          AudioStatus: 0 //播放完毕
        })
      });
    }
  },
  bindVCTextInp() {
    this.minCreatComponent();
  },
  minCreatComponent() {
    // 预计消耗时长计算
    let minute = 0;
    if (this.data.drive_type == 0) {
      // 文本驱动计算：实际字数 * （60 / 180）/ 语速
      let text = this.data.voice_text.length || 1;
      minute = text / 180 / this.data.video_set.voice_speech;
    } else {
      minute = this.form.video_duration / 60;
    }
    minute = Math.max(1, Math.ceil(minute));
    this.setData({
      minute
    })
  },
  onDragVS(event) {
    let {
      max,
      min,
      name
    } = event.currentTarget.dataset;
    this.setData({
      [name]: event.detail,
      ['video_set.' + name]: this.mapVSSliderValue(event.detail, Number(min), Number(max))
    });

    if (name == 'voice_speech') {
      this.minCreatComponent(); //重新计算消耗的时长
    }
  },
  mapVSSliderValue(oldValue, newMin = 0, newMax = 10) {
    const oldMin = 0;
    const oldMax = 100;
    const newValue = ((oldValue - oldMin) / (oldMax - oldMin)) * (newMax - newMin) + newMin;
    return parseFloat(newValue.toFixed(1)); // 保留一位小数并转换回数字
  },
  resizeDub() {
    this.selectComponent('#Dub').resize();
  },
  onChangeTabMusic(event) {
    this.data.activeMusic = event.detail.name;
    this.BGMList_finished = false;
    this.BGMListPage = 1;
    this.data.BGMList = [];
    this.getBGMList();
  },
  afterPopMusic() {
    this.selectComponent('#Music').resize();
    if (this.data.BGMList && this.data.BGMList.length) return;
    this.getBGMList();
  },
  async getBGMList() {
    if(this.BGMList_finished) return;
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.video.get-bgm-list');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        category_id: this.data.activeMusic || '',
        business_id: this.options.business_id || 0,
        page: this.BGMListPage || 1
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    let BGMList = this.data.BGMList || [];
    this.setData({
      BGMList: BGMList.concat(data.data)
    });
    if(data.current_page == data.last_page) {
      return this.BGMList_finished = true;
    }
    this.BGMListPage = data.current_page + 1;
  },
  async getEssay() {
    // 获取范文
    if (!this.data.selectRole.id) {
      app.tips('请先选择角色', 'error');
      return;
    }
    if (this.essayList && this.essayList.length) {
      this.selectEssayIndex = this.selectEssayIndex == this.essayList.length - 1 ? 0 : this.selectEssayIndex += 1;
      this.setData({
        theme: this.essayList[this.selectEssayIndex].content
      })
      return;
    }
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.paperwork.get-essay-list');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        role_id: this.data.selectRole.id,
        business_id: this.options.business_id || 0,
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    this.essayList = data;
    this.selectEssayIndex = 0;
    this.setData({
      theme: this.essayList[0].content
    })
  },
  confirmWords(event) {
    this.setData({
      words: event.detail.value,
      showWords: false
    });
  },
  async createWords() {
    // 生成文案
    if (!this.data.selectRole.id) {
      app.tips('请先选择角色', 'error');
      return;
    }
    if (!this.data.words.content) {
      app.tips('请先选择字数', 'error');
      return;
    }
    if (!this.data.theme) {
      app.tips('请输入主题内容', 'error');
      return;
    }
    wx.showLoading({
      title: '生成文案中...',
    })
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.paperwork.create');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        words_limit: this.data.words.content,
        character: this.data.selectRole.name,
        theme: this.data.theme,
        business_id: this.data.business_id,
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    wx.hideLoading();
    this.data.paperwork_total += 1;
    this.setData({
      voice_text: data.content,
      showCopywriter: false,
      paperwork_unused: this.data.paperwork_unused - 1
    });
  },
  async createVideo() {
    let {
      name,
      voice_id,
      bgm_id,
      voice_text,
      drive_type,
      video_set,
      selectRole,
      paperwork_total
    } = this.data;

    if (!this.form.body_id) {
      app.tips('请先选择数字分身');
      this.setData({
        showDigitalHuman: true
      });
      return;
    }
    if(Number(drive_type) == 0) {
      if (!name) {
        app.tips('请填写视频名称');
        return;
      }
      if (!voice_text) {
        app.tips('请填写文案');
        return;
      }
    }
    
    if (Number(drive_type) == 1 && !this.form.voice_url) {
      app.tips('请上传音频');
      return;
    }
    
    if (Number(drive_type) == 0 && !voice_id) {
      app.tips('请选择配音');
      this.setData({
        showDub: true
      });
      return;
    }

    this.form.role_name = selectRole.name;
    this.form.paperwork_total = paperwork_total;
    this.form = {
      ...this.form,
      name,
      voice_id,
      bgm_id,
      voice_text,
      drive_type,
      video_set
    }

    if(this.createVideoLock) return;
    this.createVideoLock = true;
    
    wx.showLoading({
      title: '提交创作中...',
    });
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.video.create');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        form: this.form,
        business_id: this.data.business_id,
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    this.createVideoLock = false;
    wx.hideLoading();
    if (!result) return app.tips(msg);
    this.toSpaceDetails();
  },
  toSpaceDetails() {
    wx.redirectTo({
      url: '/mircoApp/ai-create/SpaceDetails/index?tab=0&business_id=' + this.options.business_id || 0
    });
  },
  toDigitalHuman() {
    wx.navigateTo({
      url: '/mircoApp/ai-create/DigitalHuman/index?business_id=' + this.options.business_id || 0,
    });
  },
  afterDigitalHumanPop(){
    this.data.bodyList = [];
    this.bodyList_finished = false;
    this.bodyListPage = 1;
    // if (this.data.bodyList && this.data.bodyList.length) return;
    this.DigitalHumanPop();
  },
  async DigitalHumanPop() {
    if(this.bodyList_finished) return;
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.video.get-body-list');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.data.business_id,
        page: this.bodyListPage || 1
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    let bodyList = this.data.bodyList || [];
    this.setData({
      bodyList: bodyList.concat(data.data)
    });
    if(data.current_page == data.last_page) {
      return this.bodyList_finished = true;
    }
    this.bodyListPage = data.current_page + 1;
  },
  selectBody(e) {
    let {
      item
    } = e.currentTarget.dataset;
    this.form.body_id = item.id;
    this.setData({
      body: item,
      body_id: item.id
    });
  },
  onPopReachBottom(e){
    let { name } = e.currentTarget.dataset;
    if(name) this[name]();
  },
  onClickMusic(e){
    let { url, name, index } = e.currentTarget.dataset;
    if(!url) return;
    this.setData({
      [name]: index
    })
    this.setAudioURL(url);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.innerAudioContext) {
      this.innerAudioContext.destroy(); // 释放音频资源
      this.innerAudioContext = null;
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      path: '/mircoApp/ai-create/SpacePortal/index',
    };
  }
})